#include "SQLCaseExpr.h"
#include "../../visitor/SQLASTVisitor.h"

SETCALSS(SQLCaseExpr);

SQLCaseExpr::SQLCaseExpr()
{
  items = std::make_shared<std::list<SQLCaseExpr_Item_ptr>>();
}
SQLCaseExpr::~SQLCaseExpr()
{

  // for (std::list<SQLCaseExpr_Item_ptr>::iterator it = items->begin(); it != items->end(); ++it)
  // {
  //   // delete *it;
  // }
  // items->clear();

  // if (elseExpr != NULL)
  // {

  //   delete elseExpr;
  //   elseExpr = NULL;
  // }

  // if (valueExpr != NULL)
  // {

  //   delete valueExpr;
  //   valueExpr = NULL;
  // }
}
SQLExpr_ptr SQLCaseExpr::getValueExpr()
{
  return valueExpr;
}

void SQLCaseExpr::setValueExpr(SQLExpr_ptr theValueExpr)
{
  if (theValueExpr != NULL)
  {
    theValueExpr->setParent(SharedObject(SQLCaseExpr));
  }
  valueExpr = theValueExpr;
}

SQLExpr_ptr SQLCaseExpr::getElseExpr()
{
  return elseExpr;
}

void SQLCaseExpr::setElseExpr(SQLExpr_ptr theElseExpr)
{
  if (theElseExpr != NULL)
  {
    theElseExpr->setParent(SharedObject(SQLCaseExpr));
  }
  elseExpr = theElseExpr;
}

SQLCaseExpr_Item_list_ptr SQLCaseExpr::getItems()
{
  return items;
}

void SQLCaseExpr::addItem(SQLCaseExpr_Item_ptr theItem)
{
  if (theItem != NULL)
  {
    theItem->setParent(SharedObject(SQLCaseExpr));
    items->push_back(theItem);
  }
}

void SQLCaseExpr::accept0(SQLASTVisitor_ptr visitor)
{
  if (visitor->visit(SharedObject(SQLCaseExpr)))
  {
    acceptChild(visitor, valueExpr);
    acceptChild(visitor, items);
    acceptChild(visitor, elseExpr);
  }
  visitor->endVisit(SharedObject(SQLCaseExpr));
}

void SQLCaseExpr::acceptChild(SQLASTVisitor_ptr visitor, SQLCaseExpr_Item_list_ptr children)
{

  if (children->empty())
  {
    return;
  }

  std::list<SQLCaseExpr_Item_ptr>::iterator iStart = children->begin();
  std::list<SQLCaseExpr_Item_ptr>::iterator iEnd = children->end();
  std::list<SQLCaseExpr_Item_ptr>::iterator it;
  for (it = iStart; it != iEnd; ++it)
  {
    (*it)->accept(visitor);
    acceptChild(visitor, std::dynamic_pointer_cast<SQLExpr>(*it));
  }
}

void SQLCaseExpr::acceptChild(SQLASTVisitor_ptr visitor, SQLExpr_ptr child)
{
  if (child == NULL)
  {
    return;
  }

  child->accept(visitor);
}
